<?php
declare (strict_types=1);

namespace app\validate;

use think\Validate;

class organ extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'parent_id' => ['require'],
        'name' => ['require', 'checkUniqueName:thinkphp'],
        'area' => ['require'],
        'address' => ['require'],
        'person' => ['require'],
        'phone' => ['require', 'checkPhoneUnique:thinkphp', 'isMobile' => '/^1[3-9]\d{9}$/'],
        'type' => ['checkType:thinkphp']
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'parent_id.require' => "请选择所属代理",
        'name.require' => "机构名称不能为空",
        'name.checkUniqueName' => '机构名称重复',
        'area.require' => "所属地区不能为空",
        'address.require' => '详细地址不能为空',
        'person.require' => '联系人不能为空',
        'phone.require' => '手机号不能为空',
        'phone.isMobile' => '手机号格式不正确',
        'phone.checkPhoneUnique' => '此手机号已被注册',
        'type.checkType' => '省承办机构的下属不能再选择省承办类型'
    ];

    /**校验手机号是否注册过账号
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool
     */
    protected function checkPhoneUnique($value, $rule, array $data = []): bool
    {
        $id = '';
//        echo  $value;
//        print_r($data);
        // 查询该手机号是否已经被注册为管理员

        if (isset($data['user_id']) && !empty($data['user_id'])) {
            $id = $data['user_id'];
        }
        $service = app('app\service\checkField');
        return $service->accountCheckPhone($value, $id);
    }

    /**
     * 校验机构名称是否唯一
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool
     */
    protected function checkUniqueName($value, $rule, array $data = []): bool
    {
        $id = '';
        if (isset($data['id']) && !empty($data['id'])) {
            $id = $data['id'];
        }
        $service = app('app\service\checkField');
        return $service->checkInstitutionName($value, $id);
    }

    protected function checkType($value, $rule, array $data = [])
    {
        if ($data['parent_id'] !== 0 && $value == 2) {
            return false;
        } else {
            return true;
        }

    }
}
